const { API_message_500, API_message_200 } = require("../app/constants/messageAPI");
const { _menuToTree } = require("../app/utils/map-menu");
const systemService = require("../service/system.service");
const userService = require("../service/user.service");

class SystemController {
    // 通过id获取用户的角色菜单
    async getMenuListById(ctx) {
        const userId = ctx.userId;

        //获取用户信息
        const [userInfo] = await userService.getUserInformationById(userId);
        // //获取角色菜单id列表
        const [roleInfo] = await systemService.getMenuListById(userInfo.roleId);

        if (!roleInfo) {
            ctx.body = API_message_500("未找到用户角色")
            return;
        }
        const menuIds = roleInfo.menuId.split(',')
        for (let i = 0; i < menuIds.length; i++) {
            menuIds[i] = Number(menuIds[i])
        }

        // 根据id匹配菜单列表
        const menuList = await systemService.getMenuList();  
        const list = menuList.filter(item => menuIds.indexOf(Number(item.id)) !== -1);
        console.log(menuIds, menuList);
        //筛选权限菜单列表
        const res = _menuToTree(list);
        ctx.body = API_message_200(res, '操作成功');
    }

    //查询所有角色权限菜单
    async getRoleList(ctx) {

        const result = await systemService.getRoleList();

        if (result) {
            ctx.body = API_message_200(result, "查询成功")
        } else {
            ctx.body = API_message_500("查询失败")
        }
    }

    //查询所有菜单列表
    async getMenuList(ctx) {
        const menuList = await systemService.getMenuList();  
        if (menuList) {
            const result = _menuToTree(menuList);
            ctx.body = API_message_200(result, '操作成功');
        } else {
            ctx.body = API_message_500("查询失败")
        }
    }

    //新增权限
    async addRole(ctx) {
        const { menuIds, name } = ctx.request.body;
        const result = await systemService.addRole(menuIds, name);

        ctx.body = result;
    }

    // 删除权限
    async deleteRole(ctx) {
        const { roleId } = ctx.request.body;
        const result = await systemService.deleteRole(roleId);

        ctx.body = result;
    }
}

module.exports = new SystemController();